<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  #div1 {
    width: 200px;
    height: 200px;
    background: red;
    position: absolute;
  }
</style>

<script>
  window.onload = function () {
    let div1 = document.getElementById("div1")
    let disX = 0
    let disY = 0
    div1.onmousedown = function (event) {
      disX = event.clientX - div1.offsetLeft
      disY = event.clientX - div1.offsetTop


      this.onmousemove = function (event) {
        let left = event.clientX - disX
        let top = event.clientY - disY
        if (left < 0) {
          left = 0
        } else if (left > document.documentElement.clientWidth - div1.offsetWidth) {
          left = document.documentElement.clientWidth - div1.offsetWidth
        }
        if (top < 0) {
          top = 0
        }else if(top> document.documentElement.clientHeight - div1.offsetHeight){
          top = document.documentElement.clientHeight - div1.offsetHeight
        }
        div1.style.left = left + "px"
        div1.style.top = top + "px"
      }

      this.onmouseup = function () {
        div1.onmousemove = null
        div1.onmouseup = null
      }
      return false
    }

  }
</script>

<body>
  <div id="div1"></div>

</body>

</html>